<template>
  <div>
    <h2>登录</h2>
    <form @submit.prevent="login">
      <div>
        <label for="username">用户名:</label>
        <input type="text" id="username" v-model="username" required>
      </div>
      <div>
        <label for="password">密码:</label>
        <input type="password" id="password" v-model="password" required>
      </div>
      <button type="submit">登录</button>
    </form>
    <p v-if="errorMessage" style="color: red;">{{ errorMessage }}</p>
  </div>



</template>

<script>
import { ref } from 'vue';
import axios from 'axios';
import router from "@/router/router.js";

export default {
  setup() {
    const username = ref('');
    const password = ref('');
    const errorMessage = ref('');

    const login = async () => {
      try {
        const response = await axios.post('http://localhost:8080/login', {
          username: username.value,
          password: password.value
        });
        // 根据后端返回的情况进行处理，这里简化处理
        if (response.data.success) {
          // 登录成功，重定向到另一个页面
          // 这里可以使用Vue Router进行路由导航
          // window.location.href = '/dashboard';

          // 登录成功，使用 router 进行跳转
          router.push('/dashboard');
        } else {
          errorMessage.value = response.data.message;
        }
      } catch (error) {
        errorMessage.value = '登录失败，请稍后重试。';
      }
    };

    return {
      username,
      password,
      errorMessage,
      login
    };
  }
};
</script>
